#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // close()
#include <arpa/inet.h> // inet_pton()
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8080
#define BUFF_SIZE 1024

int main(){
    //创建socket
    int socket_id = socket(AF_INET,SOCK_STREAM, 0);
    if(socket_id < 0){
        perror("socket");
        return -1;
    }

    //设置服务器地址
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);

    //将字符串形式的IP地址转换为二进制形式
    int res = inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
    if(res < 0){
        perror("inet_pton");
        return -1;
    }

    res = connect(socket_id, (struct sockaddr *)&server_addr, sizeof(server_addr));

    if(res < 0){
        perror("connect");
        return -1;
    }

    printf("connect server success!\n");

    //发送数据
    char* msg = "hello world!\n";
    send(socket_id, msg, strlen(msg), 0);

    //接受数据
    char buff[BUFF_SIZE] = {0};
    res = recv(socket_id, buff, BUFF_SIZE -1, 0);
    if(res < 0){
        perror("recv");
        return -1;
    }else if(res == 0){
        printf("server close the connection\n");
        return -1;
    }

    printf("server say: %s\n", buff);
    //关闭文件描述符，关闭连接
    close(socket_id);
    return 0;
}